<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      let tree = {
        val: 1,
        left: {
          val: -2,
          left: {
            val: 1,
            left: {
              val: -1
            }
          },
          right: {
            val: 3
          }
        },
        right: {
          val: -3,
          left: {
            val: -2
          }
        }
      }
      var pathSum = function (root, targetSum) {
        if (!root) return 0
        let count = 0
        function preOrder(root) {
          if (!root) return
          backTracking(root, [root.val], root.val)
          preOrder(root.left)
          preOrder(root.right)
        }
        preOrder(root)
        return count //[1,-2] [-2,1] [-1] 因为找到路径就return了,所以还有一个 1 -2 -2 1路径没找到

        function backTracking(root, path, sum) {
          if (sum == targetSum) {
            count++
          }
          if (root.left) {
            path.push(root.left.val)
            backTracking(root.left, path, sum + root.left.val)
            path.pop()
          }
          if (root.right) {
            path.push(root.right.val)
            backTracking(root.right, path, sum + root.right.val)
            path.pop()
          }
        }
      }
      pathSum(tree, -1)
    </script>
  </body>
</html>
